package com.shangxia.monomer.study.math.algorithm.sort;

import com.alibaba.fastjson.JSONObject;

/**
 * @author zhouya38158
 * @Package com.shangxia.monomer.study.math.algorithm.sort
 * @date 2021/7/21 15:20
 */
public class Quicksort {
    public static void main(String[] args) {
        int[] arr = {2,3,5,7,9,4,1,8,6};
        System.out.println(JSONObject.toJSONString(arr));
        quickSort(arr,0,arr.length-1);
        System.out.println(JSONObject.toJSONString(arr));
    }

    public static void quickSort(int[] arr, int left, int right) {
        int pivotIndex = left + (right - left) / 2;
        int pivotValue = arr[pivotIndex];
        int i = left;
        int j = right;
        while (i <= j) {
            while (arr[i] < pivotValue) {
                i++;
            }
            while (arr[j] > pivotValue) {
                j--;
            }
            if (i <= j) {
                int tmp = arr[i];
                arr[i] = arr[j];
                arr[j] = tmp;
                i++;
                j--;
            }
            if (left < i) {
                quickSort(arr, left, j);
            }
            if (right > i) {
                quickSort(arr, i, right);
            }
        }
    }

}
